;
(function() {
  new Vue({
    el: '#workIndex',
    data: {
      data: {
        wfProjectCount: 0,
        waContractCount: 0,
        odBillCount: 0,
        duBillCount: 0,
        bpmCount: 0
      },
      permissions: JSON.parse(window.localStorage.getItem('permissions')) || [],
      projectIds: '', // 项目ID
      building: [],
      projects: [], // 项目数据
      buildingFlag: false,
      mouseenterFlag: true,
      projectId: null,
      mapInstance: null,
      curChartPanel: '实时维度',
      amapProjectName: null,
      rentState: 'DU',
      paymentState: 'OD',
      rentStateVal: '租控状态-即将到期',
      paymentStateVal: '账单状态-已逾期',
      rentStateFlag: false,
      paymentStateFlag: false,
      rentStateNum: {},
      paymentStateNum: {},
      fnProjectCount: 0, // 运营中项目数
      wfProjectCount: 0, // 筹备中项目数
      fnProjectPer: 0, // 运营中项目比例
      wfProjectPer: 0, // 筹备中项目比例
      industryChartData: {}, //远洋显示资源确认
			isSINOOCEAN: localStorage.getItem('userMes'),
      rratTaskCount: 0,
      openFlag:'',
			billFlowFlag: 'N',
      unitChartTypeList:[{'name':'合同面积','code':'HTMJ'},{'name':'单元面积','code':'DYMJ'},{'name':'单元数量','code':'DYSL'}],
      selectedUnitChartType: ['HTMJ'],

    },
    filters: {
      formatNum: function(item) {
        return hlNumberUtil.formatNum(item);
      }
    },
    methods: {
      selectUnitChartType(data){
        let text = data[0]['name']
        console.log(text);


        console.log(window.lySpace);

        if(this.curChartPanel == '缴费入驻维度') lySpace.getRzUnitChart.getProjectNumber( this.projectIds , text )
        if(this.curChartPanel == '签约维度') lySpace.getQyUnitChart.getProjectNumber( this.projectIds , text )
        if(this.curChartPanel == '实时维度') lySpace.getSsUnitChart.getProjectNumber( this.projectIds , text )
      },
			//获取账单提交流程开启
			getbillflow () {
				hlhttp.get({
				  url: 'configure/bill_bpm_config/dict',
				  success: res=> {
						this.billFlowFlag = res.open_flag
				  }
				})
			},
      // 获取意向工作流配置
			geTintentBpmConfig(){
			  hlhttp.get({
			    url: 'configure/intent_bpm_config/dict',
			    success: res=> {
						this.openFlag = res.open_flag
			    }
			  })
			},
			// 租赁资源数量
			rratCountData () {
				hlhttp.get({
					url: 'bpm/rrat_count',
					success: (data) => {
						this.rratTaskCount = data.rratTaskCount;
					}
				})
			},
      //获取数据
      getData: function() {
        var pid = [],
          cid = [],
          npid = [],
          ncid = [];

        // 解决数据加载特慢时  无法获取dom的 bug
        if ($('.third-select dd').length === 0) return false;
        if ($('.third-select .js-q').length === 0) return false;

        $('.third-select dd').each(function(index, el) {
          if ($(el).hasClass('active')) {
            pid.push($(el).attr('data-id'))
          }
          npid.push($(el).attr('data-id'))
        })
        $('.third-select .js-q').each(function(index, el) {
          if ($(el).hasClass('active')) {
            cid.push($(el).parent('.js-selected-q').attr('data-id'))
          }
          ncid.push($(el).parent('.js-selected-q').attr('data-id'))
        })

        var _this = this;

        hlhttp.get({
          url: 'workbench',
          data: {
            project_ids: pid.toString() || npid.toString() || '#',
            company_ids: cid.toString() || ncid.toString() || '#'
          },
          success: function(res) {
            _this.data = res
            _this.projects = res.projects
            if (!res.projects.length) return false;
            _this.aMap(_this.projects).multipleLocation()
          }
        })
      },
      //跳到报表
      goBaobiao: function(n) {
        if (n == 1) {
          hlUrlUtil.goTo('industry', { ddtab: true })
        }
        if (n == 2) {
          hlUrlUtil.goTo('propertyPortfolio', { ddtab: true })
        }
      },
      goToRent: function(value) {
        var self = this;
        var quanxian = JSON.parse(localStorage.getItem('permissions'))
        if(quanxian.includes('c26')){
          hlUrlUtil.goTo('renting', {
            rentState:self.rentState,
            rentPosition: value,
            ddtab: true
          })
          event.stopPropagation()
        }else{
          hl.toast('没有此权限')
        }
      },
      goToContract:function(state){
        var self = this;
        hlUrlUtil.goTo('unitContractList', {
          contractState:state,
          ddtab: true
        })
      },
      goToBillList:function(state){
        var self = this;
        hlUrlUtil.goTo('billList', {
          NAVPOSITION1:self.paymentState,
          NAVPOSITION2:state,
          ddtab: true
        })
      },
      //跳转租控
      totenant: function(buildingId) {
        hlUrlUtil.goTo('renting', {
          projectId: this.projectId,
          buildingId: buildingId,
          ddtab: true
        })
        event.stopPropagation()
      },
      //前往合同待办事项列表
      goToContractTodoList: function(n) {
        if (n == '0') return;
        var parame = {
          projectIds: this.projectIds,
          stateName: 'CT',
          ddtab: true
        }
        hlUrlUtil.goTo('todo', parame)
      },
			goRRATPage () {
				var parame = {
				  projectIds: this.projectIds,
				  stateName: 'RRAT',
				  ddtab: true
				}
				hlUrlUtil.goTo('todo', parame)
			},
			goITPage () {
				var parame = {
				  projectIds: this.projectIds,
				  stateName: 'IT',
				  ddtab: true
				}
				hlUrlUtil.goTo('todo', parame)
			},
			toCCTPage () {
				var parame = {
				  projectIds: this.projectIds,
				  stateName: 'CCT',
				  ddtab: true
				}
				hlUrlUtil.goTo('todo', parame)
			},
      //前往退租待办事项列表
      goToWithdrawTodoList: function(n) {
        if (n == '0') return;
        var parame = {
          projectIds: this.projectIds,
          stateName: 'WT',
          ddtab: true
        }
        hlUrlUtil.goTo('todo', parame)
      },
			//账单提交流程
			tobillflow () {
				if (!this.projectIds.length) return
				var parame = {
				  projectIds: this.projectIds,
				  stateName: 'BT',
				  ddtab: true
				}
				hlUrlUtil.goTo('todo', parame)
			},
      //前往流程列表
      goToMyFlowList: function() {
        if (!this.projectIds.length) return
        var parame = {
          projectIds: this.projectIds,
          ddtab: true
        }
        hlUrlUtil.goTo('myFlowList', parame)
      },
      //查看项目下楼宇详情信息
      checkBuildingMes: function(i) {
        if ($($('.js-build-btn')[i]).hasClass('hide')) {
          $($('.js-build-btn')[i]).removeClass('hide')
          $($('.programmer-arrow')[i]).addClass('updown')
        } else {
          $($('.js-build-btn')[i]).addClass('hide')
          $($('.programmer-arrow')[i]).removeClass('updown')
        }
      },
      // 获取项目楼宇列表
      getBuildingData: function(proId, proName) {
        var self = this;
        self.projectId = proId;
        self.amapProjectName = proName;
        self.buildingFlag = true;
        self.mouseenterFlag = false;

        hlhttp.get({
          url: 'project/buildings',
          data: {
            project_id: proId
          },
          success: function(data) {
            self.building = data;
          }
        })
      },
      // 展示地图信息窗口
      showInfoWindow: function(proId, selectedIndex) {
        if (this.buildingFlag) return;
        var self = this;
        self.projectId = proId;
        self.aMap(self.projects, selectedIndex).multipleLocation()
      },
      // 高德地图封装
      aMap: function(addressArr, selectedIndex) {
        var self = this;
        //构建自定义信息窗体
        function createInfoWindow(name, url) {
          var info = '<div class="work-amap-info-container">' +
            '<div class="content">' +
            '<img src="' + url + '" alt="地址信息图片">' +
            '</div>' +
            '<div class="bottom">' + name + '</div>' +
            '<div class="arrow">' +
            '<img src="https://webapi.amap.com/images/sharp.png">' +
            '</div>' +
            '</div>'

          return info
        }
        //实例化信息窗体
        function showInfo(name, url, coordinate) {
          var infoWindow = new AMap.InfoWindow({
            isCustom: true, //使用自定义窗体
            content: createInfoWindow(name, url),
            offset: new AMap.Pixel(10, -55)
          });
          infoWindow.open(self.mapInstance, coordinate);
        }
        // 地图多点定位
        function multipleLocation() {
          // 地图如果没有实例化过则先实例化地图
          if (self.mapInstance == null) {
            self.mapInstance = new AMap.Map('amap-container', {
              resizeEnable: true,
              zoom: 10,
              pitch: 20,
              // mapStyle: 'amap://styles/blue'
            });
          }

          addressArr.forEach(function(item, index) {
            // 如果指定有项目索引  则对应项目索引的项目显示绿色定位图标
            var coordinate = item.location ? item.location.split(',') : undefined
            // 兼容老数据，未有定位坐标值 则返回
            if (!coordinate) return false;
            if (selectedIndex !== undefined && selectedIndex == index) {
              var icon = new AMap.Icon({
                image: 'assets/images/location/location-green-' + (index + 1) + '.png',
                size: new AMap.Size(26, 38)
              })
              showInfo(item.name, item.preview, coordinate)
            } else {
              var icon = new AMap.Icon({
                image: 'assets/images/location/location-red-' + (index + 1) + '.png',
                size: new AMap.Size(26, 38)
              })
            }

            var marker = new AMap.Marker({
              icon: icon,
              position: coordinate,
              // offset: new AMap.Pixel(-0.5,-0.5),
              map: self.mapInstance
            });

          })
          self.mapInstance.setFitView();
        }

        return {
          multipleLocation: multipleLocation
        }
      },
      // 切换图表维度
      selectChartPanel: function(val) {
        this.curChartPanel = val;

        let text = '单元面积'
        this.selectedUnitChartType = ['HTMJ']

        if(this.curChartPanel == '缴费入驻维度') lySpace.getRzUnitChart.getProjectNumber( this.projectIds , text )
        if(this.curChartPanel == '签约维度') lySpace.getQyUnitChart.getProjectNumber( this.projectIds , text )
        if(this.curChartPanel == '实时维度') lySpace.getSsUnitChart.getProjectNumber( this.projectIds , text )
      },
      backToAmap: function() {
        this.buildingFlag = false;
        this.amapProjectName = null;
      },
      // 获取租控状态统计数量
      getRentStateCount() {
        var self = this;
        hlhttp.get({
          url: 'project/rent_state_count',
          data: {
            'rent_state': self.rentState,
            'project_ids': self.projectIds || '#'
          },
          success: function(data) {
            console.log(data)
            self.rentStateNum = data;
          }
        })
      },
      // 获取账单支付状态数量
      getBillPaymentStateCount() {
        var self = this;
        hlhttp.get({
          url: 'bill/payment_state_count',
          data: {
            'bill_state': self.paymentState,
            'project_ids': self.projectIds || '#'
          },
          success: function(data) {
            self.paymentStateNum = data;
          }
        })
      },
      handleRentState(state) {
        this.rentState = state
        if (state == 'VA') {
          this.rentStateVal = '租控状态-空置'
        }
        if (state == 'DU') {
          this.rentStateVal = '租控状态-即将到期'
        }
        if (state == 'IP') {
          this.rentStateVal = '租控状态-即将履约'
        }
        this.getRentStateCount()
      },
      handleBillState(state) {
        this.paymentState = state
        if (state == 'DU') {
          this.paymentStateVal = '账单状态-即将到期'
        }
        if (state == 'OD') {
          this.paymentStateVal = '账单状态-已逾期'
        }
        this.getBillPaymentStateCount()
      },
      // 获取项目图表
      getProjectChartData() {
        var self = this;
        hlhttp.get({
          url: 'user/fn_project_count,wf_project_count',
          data: {
            'project_ids': self.projectIds || '#'
          },
          success: function(data) {
            var per = (data.fnProjectCount / (Number(data.fnProjectCount) + Number(data.wfProjectCount)) * 100).toFixed(2)
            self.fnProjectCount = Number(data.fnProjectCount)
            self.wfProjectCount = Number(data.wfProjectCount)
            self.fnProjectPer = per
            self.wfProjectPer = (100 - per).toFixed(2)
          }
        })
      },
      // 获取行业面积图表
      getIndustryAreaChartData() {
        var self = this;
        var date = hlDateUtil.countSeveralDaysTime(new Date(), -1)

        // 获取行业字典匹配
        var getIndustryDict = (fn) => {
          hlhttp.get({
            url: 'configure/industry/dict',
            success: function(data) {
              fn(data)
            }
          })
        }
        // 匹配行业字典 返回行业名
        var getName = (data, dict) => {
          var name = null;
          data.forEach((el, i) => {
            if (el.dictCode == dict) name = el.dictName
          })

          return name
        }

        hlhttp.get({
          url: 'report/acreage_by_industry',
          data: {
            date: date
          },
          success: function(data) {
            if (data.industryList.length == 0) return false;
            getIndustryDict((industryDict) => {
              const industryList = data.industryList
              let totalPer = 0
              let totalArea = industryList.reduce((total, obj) => {
                return total + obj.acreage
              }, 0)

              industryList.forEach((el, i) => {
                if (i < industryList.length - 1) {
                  el['percentage'] = Number((el.acreage / totalArea * 100).toFixed(2))
                  totalPer += el['percentage']
                }
                if (i == industryList.length - 1) {
                  el['percentage'] = Number((100 - totalPer).toFixed(2))
                }

                el['name'] = getName(industryDict, el.industryType)
              })

              self.industryChartData = {
                'companyCount':data.companyCount,
                'industryList':data.industryList
              }
            })
          }
        })
      }
    },
    mounted: function() {
      this.geTintentBpmConfig()
			this.getbillflow()
      var _this = this;

			if (this.isSINOOCEAN.indexOf('SINOOCEAN') > -1) {
				this.rratCountData()
			}

      getProduct(function(arr) {
        // 获取所有的项目ID并传递给列表
        if (arr[1].length) {
          _this.projectIds = arr[1].join(',')
        }
        _this.getData()
        _this.getRentStateCount()
        _this.getBillPaymentStateCount()
        _this.getProjectChartData()
        _this.getIndustryAreaChartData()
        if(_this.curChartPanel == '实时维度') lySpace.getSsUnitChart.getProjectNumber( _this.projectIds , '合同面积' )
        _this.permissions = JSON.parse(window.localStorage.getItem('permissions'))
      }, function(arr) {
        if(arr[0].length) _this.projectIds = arr[0].join(',')

        setTimeout(function() {
          _this.getData()
          _this.getRentStateCount()
          _this.getBillPaymentStateCount()
          if(_this.curChartPanel == '实时维度') lySpace.getSsUnitChart.getProjectNumber( _this.projectIds , '合同面积' )
        }, 200);
      }, function(arr) {
        if(arr[0].length) _this.projectIds = arr[0].join(',')

        _this.getData()
        _this.getRentStateCount()
        _this.getBillPaymentStateCount()
        if(_this.curChartPanel == '实时维度') lySpace.getSsUnitChart.getProjectNumber( _this.projectIds , '合同面积' )
      })


    }
  })
}())
